package com.restTemplate.service;

import com.restTemplate.entity.Info;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


/**
 * @author CKC
 * @DateTime 2021/11/22 20:16
 */
@Service
public class GetBaiduInfo {

    @Autowired
    private RestTemplate restTemplate;


    public void getInfo(String key) {
        String results = restTemplate.getForObject("http://www.baidu.com/s?wd=" + key, String.class);
        System.out.println(results);
    }

    /**
     * 将参数封装到Map集合中
     */
    public void getForEntity1() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "ckc");
        map.put("age", 18);
        String url = "https://www.ceshi.com?name={name}&age={age}";
        //参数1: url  具体参数值使用 ‘{paramName}’ paramName 是map中key
        //参数2: 返回值的类型
        //参数3: map集合
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, map);
        String body = responseEntity.getBody();//获取 结果
        HttpHeaders headers = responseEntity.getHeaders();//获取响应头信息
    }

    /**
     * 将参数直接拼接到URL中
     */
    public void getForEntity2(String name, Integer age) throws UnsupportedEncodingException {
        //中文需要URLEncoder.encode 来转码
        String url = "https://www.ceshi.com?name=" + URLEncoder.encode(name, StandardCharsets.UTF_8.toString()) + "&age" + age;
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);

    }

    public void postForEntity1() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "ckc");
        map.put("age", 18);
        String url = "https://www.ceshi.com";
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, map, String.class);
    }

    public void postForEntity2() {
        String name = "ckc";
        Integer age = 18;
        String url = "https://www.ceshi.com?name={1}&age={2}";
        //{1},{2} 1,2表示参数的位置 下面最后两个参数
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, null, String.class, name, age);
    }

    /**
     * 传递JSON数据
     */
    public void postForEntity3() {
        String url = "https://www.ceshi.com/hello";
        Info info = new Info();
        info.setAge(18);
        info.setName("ckc");
        ResponseEntity<Info> forEntity = restTemplate.postForEntity(url, info, Info.class);
    }


}
